﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SharedGenomics.Core
{
    public class TextFileReader : IEnumerable<string>
    {
        public TextFileReader(string filePath)
            : this(new TextFileReaderFileState(filePath))
        { }

        public TextFileReader(Stream stream)
            : this(new TextFileReaderStreamState(stream))
        { }

        public TextFileReader(ITextFileReaderState state)
        {
            state.ThrowIfNull("state");
            this.State = state;
        }

        public static void IterateFile(string filePath, Action<string> lineAction)
        {
            lineAction.ThrowIfNull("lineAction");

            TextFileReader r = new TextFileReader(filePath);

            foreach (string line in r)
            {
                lineAction(line);
            }
        }

        public IEnumerator<string> GetEnumerator()
        {
            using (var reader = this.State.OpenReader())
            {
                string currentLine;
                while ((currentLine = reader.ReadLine()) != null)
                {
                    yield return currentLine;
                }
            }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        private ITextFileReaderState State { get; set; }
    }
}
